<template>
  <div class="coupon-management">
    <el-card>
      <div slot="header" class="clearfix">
        <span>优惠券管理</span>
        <el-button style="float: right" type="primary" @click="handleAdd" icon="el-icon-plus">
          新增优惠券
        </el-button>
      </div>

      <!-- 搜索栏 -->
      <!-- <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="优惠券名称">
            <el-input v-model="searchForm.title" placeholder="请输入优惠券名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="优惠券类型">
            <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
              <el-option label="满减券" :value="1"></el-option>
              <el-option label="折扣券" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="使用场景">
            <el-select v-model="searchForm.scene" placeholder="请选择场景" clearable>
              <el-option label="全场通用" :value="1"></el-option>
              <el-option label="指定分类" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option label="启用" :value="1"></el-option>
              <el-option label="禁用" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div> -->

      <!-- 优惠券列表 -->
      <el-table :data="couponList" v-loading="loading" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="优惠券名称" min-width="150"></el-table-column>
        <el-table-column label="优惠券类型" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.type === 1 ? 'success' : 'warning'">
              {{ scope.row.type === 1 ? '满减券' : '折扣券' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="优惠金额/折扣" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.type === 1">¥{{ scope.row.price }}</span>
            <span v-else>{{ scope.row.price }}折</span>
          </template>
        </el-table-column>
        <el-table-column prop="min_price" label="最低消费" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.min_price }}
          </template>
        </el-table-column>
        <el-table-column prop="money" label="售价" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.money }}
          </template>
        </el-table-column>
        <el-table-column label="使用场景" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.scene === 1 ? 'primary' : 'info'">
              {{ scope.row.scene === 1 ? '全场通用' : '指定分类' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="指定分类" width="120" v-if="false">
          <template slot-scope="scope">
            <span v-if="scope.row.scene === 2">{{ getCategoryName(scope.row.category_id) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="exp_day" label="有效期(天)" width="100"></el-table-column>
        <el-table-column prop="desc" label="描述" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column label="状态" width="80">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="160"></el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              @click="handleEdit(scope.row)" 
              icon="el-icon-edit" 
              type="primary"
            >
              编辑
            </el-button>
            <el-button 
              size="mini" 
              :type="scope.row.status == 1 ? 'warning' : 'success'" 
              :icon="scope.row.status == 1 ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"
              @click="handleDelete(scope.row)"
            >
              {{ scope.row.status == 1 ? '下架' : '上架' }}
            </el-button>
            <el-button 
              size="mini" 
              type="info" 
              icon="el-icon-gift"
              @click="handleGift(scope.row)"
            >
              赠送
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑优惠券弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        :model="couponForm"
        :rules="couponRules"
        ref="couponForm"
        label-width="100px"
      >
        <el-form-item label="优惠券名称" prop="title">
          <el-input v-model="couponForm.title" placeholder="请输入优惠券名称"></el-input>
        </el-form-item>
        
        <el-form-item label="优惠券类型" prop="type">
          <el-radio-group v-model="couponForm.type" @change="handleTypeChange">
            <el-radio :label="1">满减券</el-radio>
            <el-radio :label="2">折扣券</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item :label="couponForm.type === 1 ? '优惠金额' : '折扣'" prop="price">
          <el-input v-model="couponForm.price" :placeholder="couponForm.type === 1 ? '请输入优惠金额' : '请输入折扣(如0.8表示8折)'">
            <template slot="append" v-if="couponForm.type === 1">元</template>
            <template slot="append" v-else>折</template>
          </el-input>
        </el-form-item>

        <el-form-item label="最低消费" prop="min_price">
          <el-input v-model="couponForm.min_price" placeholder="请输入最低消费金额">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>


        <el-form-item label="售价" prop="money">
          <el-input v-model="couponForm.money" placeholder="请输入售价">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>

        <el-form-item label="使用场景" prop="scene">
          <el-radio-group v-model="couponForm.scene" @change="handleSceneChange">
            <el-radio :label="1">全场通用</el-radio>
            <el-radio :label="2">指定分类</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="商品分类" prop="category_id" v-if="couponForm.scene === 2">
          <el-select v-model="couponForm.category_id" placeholder="请选择商品分类" style="width: 100%">
            <el-option v-for="category in categoryOptions" :key="category.id" :label="category.name" :value="category.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="有效期" prop="exp_day">
          <el-input v-model="couponForm.exp_day" placeholder="请输入有效期天数">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>

        <el-form-item label="描述" prop="desc">
          <el-input
            type="textarea"
            v-model="couponForm.desc"
            placeholder="请输入优惠券描述"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 赠送优惠券弹窗 -->
    <el-dialog
      title="赠送优惠券"
      :visible.sync="giftDialogVisible"
      width="400px"
      @close="resetGiftForm"
    >
      <el-form
        :model="giftForm"
        :rules="giftRules"
        ref="giftForm"
        label-width="100px"
      >
        <el-form-item label="优惠券名称">
          <el-input v-model="giftForm.title" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="用户手机号" prop="mobile">
          <el-input 
            v-model="giftForm.mobile" 
            placeholder="请输入用户手机号"
            maxlength="11"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="giftDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleGiftSubmit" :loading="giftLoading">确定赠送</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchCouponList, createCoupon, updateCoupon, deleteCoupon, updateCouponStatus, giftCoupon } from '@/api/shopping'
import { categoryList } from '../../../libs/api'

export default {
  name: 'DiscountCouponList',
  data() {
    return {
      loading: false,
      submitLoading: false,
      couponList: [],
      searchForm: {
        title: '',
        type: '',
        scene: '',
        status: ''
        
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogTitle: '新增优惠券',
      couponForm: {
        id: '',
        title: '',
        type: '2',
        price: '',
        min_price: '',
        money: '',
        scene: '1',
        category_id: '',
        exp_day: '',
        desc: ''
      },
      couponRules: {
        title: [
          { required: true, message: '请输入优惠券名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择优惠券类型', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入优惠金额或折扣', trigger: 'blur' }
        ],
        min_price: [
          { required: true, message: '请输入最低消费金额', trigger: 'blur' }
        ],
        money: [
          { required: true, message: '请输入售价', trigger: 'blur' }
        ],
        scene: [
          { required: true, message: '请选择使用场景', trigger: 'change' }
        ],
        category_id: [
          { 
            validator: (rule, value, callback) => {
              if (this.couponForm.scene === '2' && !value) {
                callback(new Error('请选择商品分类'))
              } else {
                callback()
              }
            }, 
            trigger: 'change' 
          }
        ],
        exp_day: [
          { required: true, message: '请输入有效期天数', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请输入优惠券描述', trigger: 'blur' }
        ]
      },
      categoryOptions: [],
      // 赠送相关
      giftDialogVisible: false,
      giftLoading: false,
      giftForm: {
        id: '',
        title: '',
        mobile: ''
      },
      giftRules: {
        mobile: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCouponList()
    this.loadCategoryOptions()
  },
  methods: {
    // 获取优惠券列表
    async getCouponList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          limit: this.pagination.pageSize,
          ...this.searchForm
        }
        const response = await fetchCouponList(params)
        if (response.code === 1) {
          this.couponList = response.data || []
          this.pagination.total = response.total || 0
        } else {
          this.$message.error(response.msg || '获取优惠券列表失败')
        }
      } catch (error) {
        this.$message.error('获取优惠券列表失败')
        console.error('获取优惠券列表失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.getCouponList()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        title: '',
        type: '',
        scene: '',
        status: ''
      }
      this.pagination.currentPage = 1
      this.getCouponList()
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.getCouponList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.getCouponList()
    },

    // 新增优惠券
    handleAdd() {
      this.dialogTitle = '新增优惠券'
      this.dialogVisible = true
      this.resetForm()
    },
    // 编辑优惠券
    handleEdit(row) {
      this.dialogTitle = '编辑优惠券'
      this.dialogVisible = true
      this.couponForm = { ...row }
    },
    // 下架/上架优惠券
    handleDelete(row) {
      const action = row.status == 1 ? '下架' : '上架'
      this.$confirm(`确定要${action}该优惠券吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await deleteCoupon(row.id)
          if (response.code === 1) {
            this.$message.success(`${action}成功`)
            this.getCouponList()
          } else {
            this.$message.error(response.msg || `${action}失败`)
          }
        } catch (error) {
          this.$message.error(`${action}失败`)
          console.error(`${action}失败:`, error)
        }
      })
    },

    // 状态改变
    async handleStatusChange(row) {
      try {
        const response = await updateCouponStatus(row.id, row.status)
        if (response.code === 1) {
          this.$message.success('状态修改成功')
        } else {
          this.$message.error(response.msg || '状态修改失败')
          // 恢复原状态
          row.status = row.status === 1 ? 0 : 1
        }
      } catch (error) {
        this.$message.error('状态修改失败')
        // 恢复原状态
        row.status = row.status === 1 ? 0 : 1
        console.error('状态修改失败:', error)
      }
    },

    // 类型改变
    handleTypeChange() {
      this.couponForm.price = ''
    },

    // 场景改变
    handleSceneChange() {
      this.couponForm.category_id = ''
    },

    // 提交表单
    handleSubmit() {
      this.$refs.couponForm.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
        try {
          const formData = { ...this.couponForm }
          // 如果是全场通用，清空分类ID
          if (formData.scene === '1') {
            formData.category_id = ''
          }
          
          const response = this.couponForm.id 
            ? await updateCoupon(formData)
            : await createCoupon(formData)
              
            if (response.code === 1) {
              this.$message.success(this.couponForm.id ? '更新成功' : '创建成功')
              this.dialogVisible = false
              this.getCouponList()
            } else {
              this.$message.error(response.msg || '操作失败')
            }
          } catch (error) {
            this.$message.error('操作失败')
            console.error('操作失败:', error)
          } finally {
            this.submitLoading = false
          }
        }
      })
    },

    // 加载分类选项
    async loadCategoryOptions() {
      try {
        const res = await categoryList()
        if (res.code === 1 && res.data) {
          // 将树形分类数据展平为选项数组，只获取二级分类
          this.categoryOptions = this.flattenCategories(res.data)
        } else {
          this.$message.error('获取分类列表失败')
          this.categoryOptions = []
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        this.$message.error('获取分类列表失败')
        this.categoryOptions = []
      }
    },

    // 将分类树展平为列表，只获取二级分类
    flattenCategories(categories) {
      const allCategories = []
      const flatten = (cats) => {
        cats.forEach((category) => {
          // 只添加二级分类（level === 2）
          if (category.level === 2) {
            allCategories.push({
              id: category.id,
              name: category.name
            })
          }
          // 递归处理子分类
          if (category.children && category.children.length > 0) {
            flatten(category.children)
          }
        })
      }
      flatten(categories)
      return allCategories
    },

    // 获取分类名称
    getCategoryName(categoryId) {
      const category = this.categoryOptions.find(item => item.id === categoryId)
      return category ? category.name : '未知分类'
    },

    // 赠送优惠券
    handleGift(row) {
      this.giftForm = {
        id: row.id,
        title: row.title,
        mobile: ''
      }
      this.giftDialogVisible = true
    },

    // 提交赠送
    handleGiftSubmit() {
      this.$refs.giftForm.validate(async (valid) => {
        if (valid) {
          this.giftLoading = true
          try {
            const response = await giftCoupon({
              id: this.giftForm.id,
              mobile: this.giftForm.mobile
            })
            if (response.code === 1) {
              this.$message.success('赠送成功')
              this.giftDialogVisible = false
            } else {
              this.$message.error(response.msg || '赠送失败')
            }
          } catch (error) {
            this.$message.error('赠送失败')
            console.error('赠送失败:', error)
          } finally {
            this.giftLoading = false
          }
        }
      })
    },

    // 重置赠送表单
    resetGiftForm() {
      this.giftForm = {
        id: '',
        title: '',
        mobile: ''
      }
      this.$nextTick(() => {
        this.$refs.giftForm && this.$refs.giftForm.clearValidate()
      })
    },

    // 重置表单
    resetForm() {
      this.couponForm = {
        id: '',
        title: '',
        type: '2',
        price: '',
        min_price: '',
        money: '',
        scene: '1',
        category_id: '',
        exp_day: '',
        desc: ''
      }
      this.$nextTick(() => {
        this.$refs.couponForm && this.$refs.couponForm.clearValidate()
      })
    }
  }
}
</script>

<style scoped>
.coupon-management {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
